const fs = require('fs');
const httpClient = require('./http_client');
const Core = require('@alicloud/pop-core');
const RPCClient = Core.RPCClient;
const DateTime = require("./datetime");

class AliInterface {
    printError(error) {
        if (global.log) {
            global.log.error(error);
        } else {
            console.error(error);
        }
    }
    getRPCClient(accessKeyId, accessKeySecret, endpoint, apiVersion) {
        this.client = new RPCClient({
            accessKeyId: accessKeyId,
            secretAccessKey: accessKeySecret,
            endpoint: endpoint,
            apiVersion: apiVersion
        });
    }
    //阿里云公共SDK调用云端服务获取Access Token，获取一次可以用很长时间
    async accessToken(filePath) {
        let record = null;
        let path = filePath+"access_token.txt";
        try {
            let file = fs.readFileSync(path);
            record = JSON.parse(file);
        } catch (error) {
            this.printError(error);
        }
        const now = new DateTime();
        if (record==null || record.ExpireTime<now.timestamp()) {
            let token = null;
            try {
                let data = await this.client.request('CreateToken');
                if (data.ErrMsg && data.ErrMsg.length) {
                    throw data.ErrMsg;
                }
                token = data.Token.Id;
                data.Token.ExpireTime -= 60;
                fs.writeFileSync(path, JSON.stringify(data.Token));
            } catch (error) {
                this.printError(error);
            }
            return token;
        } else {
            return record.Id;
        }
    }
}

class AliRESTful extends AliInterface {
    constructor(cfg) {
        super();
        this.cfg = cfg;
        this.getRPCClient(cfg.accessKeyId, cfg.accessKeySecret, 'http://nls-meta.cn-shanghai.aliyuncs.com', '2019-02-28');
    }
    async tts(text, voice='xiaoyun') {
        const token = await this.accessToken(this.cfg.filePath);
        const task = {
            appkey : this.cfg.appkey,
            token : token,
            text : text,
            format : 'mp3',
            sample_rate : 16000,
            voice : voice,//发音人，可选，默认是xiaoyun。
            volume : 90//音量，范围是0~100，可选，默认50。
            // speech_rate 语速，范围是-500~500，可选，默认是0。
            // speech_rate : 0,
            // pitch_rate 语调，范围是-500~500，可选，默认是0。
            // pitch_rate : 0
        };
        const bodyContent = JSON.stringify(task);
        const mp3 = await httpClient.httpsPost('https://nls-gateway.cn-shanghai.aliyuncs.com/stream/v1/tts', bodyContent, 'json');
        if (!mp3.headers || mp3.headers['content-type']!='audio/mpeg') {
            this.printError(mp3.body.toString());
            return null;
        } else {
            return mp3.body;
        }
    }
}

class AliVideo extends AliInterface {
    constructor(cfg) {
        super();
        this.cfg = cfg;
        this.getRPCClient(cfg.accessKeyId, cfg.accessKeySecret, 'http://vod.cn-shanghai.aliyuncs.com', '2017-03-21');
    }
    //上传新视频,多标签用逗号分隔
    //https://help.aliyun.com/document_detail/55407.html?spm=a2c4g.11186623.4.5.c41d276dXcmTPK
    async newVideo(title,fileName,tags,coverURL) {
        let p = {
            Title: title,
            FileName: fileName
        }
        if (tags) {
            p.Tags = tags;
        }
        if (coverURL) {
            p.CoverURL = coverURL;
        }
        try {
            let response = await this.client.request("CreateUploadVideo", p, {});
            let ret = {requestId:response.RequestId, videoId:response.VideoId, address:response.UploadAddress, auth:response.UploadAuth, };
            return ret;
        } catch (error) {
            return {err:error.data};
        }
    }
    //覆盖上传视频
    async refreshVideo(videoId) {
        try {
            let response = await this.client.request("RefreshUploadVideo", {VideoId: videoId}, {});
            let ret = {requestId:response.RequestId, address:response.UploadAddress, auth:response.UploadAuth, };
            return ret;
        } catch (error) {
            return {err:error.data};
        }
    }
    //获取播放凭证
    //https://help.aliyun.com/document_detail/52833.html?spm=a2c4g.11186623.4.1.678a1fc1fnEVS8
    async getVideoPlayAuth(videoId) {
        try {
            let response = await this.client.request("GetVideoPlayAuth", {VideoId: videoId}, {});
            let ret = {requestId:response.RequestId, auth:response.PlayAuth};
            // base metadata
            if (response.VideoMeta){
                ret.coverURL = response.VideoMeta.CoverURL;
            }
            return ret;
        } catch (error) {
            return {err:error.data};
        }
    }
}

class AliOSS extends AliInterface {
    constructor(cfg) {
        super();
        this.cfg = cfg;
        this.getRPCClient(cfg.accessKeyId, cfg.accessKeySecret, 'https://sts.aliyuncs.com', '2015-04-01');
    }
    getOSS() {
        const params = {
            'RoleArn': this.cfg.RoleArn,
            'RoleSessionName': this.cfg.RoleSessionName
        };
        //发起请求
        this.client.request('AssumeRole', params).then((result) => {
            // console.log(result);
            const ossCfg = {
                region: this.cfg.region,
                accessKeyId: result.Credentials.AccessKeyId,
                accessKeySecret: result.Credentials.AccessKeySecret,
                stsToken: result.Credentials.SecurityToken,
                bucket: this.cfg.bucket,
                expires: ~~(Date.now()/1000)+30*60
            }
            fs.writeFileSync(this.cfg.filePath+"oss.txt", JSON.stringify(ossCfg));
        }, (err) => {
            this.printError(err);
        });
    }
}

class AliSms extends AliInterface {
    constructor(cfg) {
        super();
        this.cfg = cfg;
        this.getRPCClient(cfg.accessKeyId, cfg.accessKeySecret, 'https://dysmsapi.aliyuncs.com', '2017-05-25');
    }
    async sendSms(params) {
        let ret = null;
        try {
            const result = await this.client.request('SendSms', params, {method: 'POST'});
            ret = [result.Code=='OK'?0:1, result.Message];
        } catch (error) {
            this.printError(error);
            ret = [1, '短信发送失败'];
        }
        return ret;
    }
}

class AliIDcard extends AliInterface {
    constructor(cfg) {
        super();
        this.cfg = cfg;
    }
    async verifyIDcard(name, idcard) {
        try {
            let ret = await httpClient.httpPost('http://checkone.market.alicloudapi.com/chinadatapay/1882', `identifyNum=${identifyNum}&userName=${encodeURI(userName)}`, 'from-urlencoded', {Authorization:this.cfg.appcode});
            ret = ret.body.toString();
            if (ret.length>1) {
                const r = JSON.parse(ret);
                if (r.code=="10000" && r.data) {
                    return parseInt(r.data.result);
                } else {
                    return 4;
                }
            } else {
                return 5;
            }
        } catch (error) {
            this.printError(error);
            return 5;
        }
    }
}

class AliIDcard2 extends AliInterface {
    constructor(cfg) {
        super();
        this.cfg = cfg;
    }
    async verifyIDcard(name, idcard) {
        try {
            //httpsGet 缺少header设置
            let ret = await httpClient.httpsGet(`https://safrvpos.market.alicloudapi.com/id2meta?identifyNum=${idcard}&userName=${encodeURI(name)}`, {Authorization:'APPCODE ' + this.cfg.AppCode});
            if(ret.body == null)
                return 6;
            ret = ret.body.toString();
			// console.log(ret);
            if (ret.length>1) {
                const r = JSON.parse(ret);
                if (r.code=="200") {
                    if (r.data.bizCode==1) {
                        return 0;
                    } else {
                        return 7;
                    }
                } else {
                    return parseInt(r.code) != 0 ? parseInt(r.code) : 4;
                }
            } else {
                return 5;
            }
        } catch (error) {
            this.printError(error);
            return 5;
        }
    }
}

class AliMoblieCheckout extends AliInterface {
    constructor(cfg) {
        super();
        this.cfg = cfg;
        this.getRPCClient(cfg.accessKeyId, cfg.accessKeySecret, 'https://dypnsapi.aliyuncs.com', '2017-05-25');
        this.requestOption = {
            method: 'POST',
            formatParams: false
        };
    }
    async getMobile(token, customID) {
        let ret = null;
        try {
            const result = await this.client.request('GetMobile', {AccessToken:token, OutId:customID}, this.requestOption);
            ret = [0, result];
        } catch (error) {
            ret = [1, error];
        }
        return ret;
    }
}

module.exports.AliRESTful = AliRESTful;//文字转语音
module.exports.AliVideo = AliVideo;//播放视频
module.exports.AliOSS = AliOSS;//阿里OSS
module.exports.AliSms = AliSms;//短信
module.exports.AliIDcard = AliIDcard;//身份证验证
module.exports.AliIDcard2 = AliIDcard2;//身份证验证
module.exports.AliMoblieCheckout = AliMoblieCheckout;//手机本机号码校验
